package com.googlecode.javatools.classparser.types.impl;

import com.googlecode.javatools.classparser.types.ConstantEntry;
import com.googlecode.javatools.classparser.types.ConstantPool;

public class ConstantPoolImpl implements ConstantPool
{
	private final ConstantEntry[] constantPool;

	public ConstantPoolImpl(final ConstantEntry[] constantPool)
	{
		this.constantPool = constantPool;
	}

	public ConstantEntry entryAt(final int entryIndex)
	{
		if (entryIndex < 0 || entryIndex >= constantPool.length)
		{
			throw new IllegalStateException("Illegal constant pool index : " + entryIndex);
		}

		return constantPool[entryIndex];
	}

	public String valueAtIndex(final int entryIndex)
	{
		if (entryIndex < 0 || entryIndex >= constantPool.length)
		{
			throw new IllegalStateException("Illegal constant pool index : " + entryIndex);
		}

		final ConstantEntry entry = entryAt(entryIndex);
		if (entry == null)
		{
			return "";
		}

		return slashesToDots(entryAt(entry.getNameIndex()).toUTF8());
	}

	private String slashesToDots(final String s)
	{
		return s.replace('/', '.');
	}
}
